/*
 * @Author: chunlai
 * @Date: 2023-07-25 09:48:14
 * @LastEditTime: 2025-08-21 14:12:16
 * @LastEditors: minsheng_insurance_agency_zhoucl
 * @FilePath: \02.bldinsure\src\translate\validate\customer.js
 * @Description: 客户信息录入校验规则
 */
import { getCacheValue } from "@/methods/cache.js";
import { userAge } from "@/methods/globals.js";
import {
  bmiRuleCheck,
  idTypeRuleCheck,
  validDateRuleCheck,
  guojiRuleCheck,
  phoneRuleCheck,
  occupRuleCheck,
  partTimeJobCheck,
  grpNameCheck,
  sexRuleCheck,
  birthDayRuleCheck,
  zipCodeRuleCheck,
  writeRevenueFileCheck,
  insrRelaToTbr,
} from "@/translate/validate/fileds.js";
import {
  checkStrMaxNum,
  IdentityCodeValid,
  yearDiffValue,
  dayDiffValue,
  emptyFieldCheck,
} from "@/methods/userinfos.js";
import constantRules from "@/methods/rules.js";

const { regexMap } = constantRules;
/**
 * 校验客户信息
 * @param {*} userModel 字段模板
 * @param {*} infoData
 * @param {*} utype
 * @returns
 */
export const validUserInfo = (userModel, infoData, utype = "") => {
  // console.log("validUserInfo", userModel)
  const proCompName = getCacheValue("insert", "compEngName");
  let obj = {
    msg: "",
    status: true,
    target: "",
  };
  let breakTips = [];
  // 与投保人的关系
  if (userModel.relationToAppnt !== undefined) {
    obj = tbRelateCheck(infoData, utype, userModel);
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  // 与被保人的关系（受益人）
  if (userModel.relationToInsured !== undefined) {
    obj = tbRelateCheck(infoData, utype, userModel);
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  // 姓名校验
  if (userModel.name !== undefined) {
    obj = nameCheckRule(infoData.name);
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  //证件类型校验
  if (userModel.idType !== undefined) {
    obj = idTypeRuleCheck(infoData);
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  //证件号码校验
  if (userModel.idNum !== undefined) {
    obj = idNumCheck(infoData);
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  // 证件起期校验
  if (userModel.validDate !== undefined) {
    obj = validDateRuleCheck(infoData);
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  // 证件止期校验
  if (userModel.validDateEnd !== undefined) {
    obj = validDateEndCheck(infoData);
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  // 性别校验
  if (userModel.sex !== undefined) {
    obj = sexRuleCheck(infoData, utype); //utype必传
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  // 出生日期
  if (userModel.birthDate !== undefined) {
    obj = birthDayRuleCheck(infoData, utype); //utype必传
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }

  // 投保区域校验
  if (utype.indexOf("被保人") != -1 || utype.indexOf("投保人") != -1) {
    const insuAreaCalib = getCacheValue("page", "insuAreaCalibration") || [];
    const mcode = getCacheValue("insert", "mainRiskCode");
    if (insuAreaCalib.length > 0 && insuAreaCalib.includes(mcode)) {
      obj = insuAddrCheck(infoData);
      if (!obj.status) return obj;
      if (obj.breakTips) {
        breakTips.push(obj.breakTips);
      }
    }
  }

  // 地址1
  if (userModel.permanentAddress !== undefined) {
    obj = addrCheck(infoData, "permanentAddress");
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  // 地址2
  if (userModel.postalPermanentAddress !== undefined) {
    obj = addrCheck(infoData, "postalPermanentAddress");
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  // 地址3
  if (userModel.homePermanentAddress !== undefined) {
    obj = addrCheck(infoData, "homePermanentAddress");
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  // 国籍
  if (userModel.nationality !== undefined) {
    obj = guojiRuleCheck(infoData);
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  //手机号
  if (userModel.phone !== undefined) {
    obj = phoneRuleCheck(infoData);
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  if (userModel.occupationCode !== undefined) {
    obj = occupRuleCheck(infoData, utype, proCompName); //utype必传
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  //工作单位
  if (userModel.grpName !== undefined) {
    obj = grpNameCheck(infoData, utype); //utype必传
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }

  //工作内容
  if (userModel.jobContent !== undefined) {
    obj = emptyFieldCheck(infoData, "jobContent", "工作内容");
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  // 学历
  if (userModel.degree !== undefined) {
    obj = emptyFieldCheck(infoData, "degree", "学历");
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  // 户籍
  if (userModel.rgtAreaName !== undefined) {
    obj = emptyFieldCheck(infoData, "rgtAreaName", "户籍");
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  // 民族
  if (userModel.nationCode !== undefined) {
    obj = emptyFieldCheck(infoData, "nationCode", "民族");
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  // 年收入
  if (userModel.income !== undefined) {
    obj = emptyFieldCheck(infoData, "income", "年收入");
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  // 收入来源
  if (userModel.incomeSource !== undefined) {
    obj = emptyFieldCheck(infoData, "incomeSource", "收入来源");
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  //兼职
  if (userModel.partTimeJob !== undefined) {
    obj = partTimeJobCheck(infoData);
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  // 身高 体重
  if (userModel.height !== undefined) {
    obj = bmiRuleCheck(infoData, utype); //utype必传
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }

  // 邮编
  if (userModel.zipCode !== undefined) {
    obj = zipCodeRuleCheck(infoData);
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }

  //社保
  if (userModel.socialInsuFlag !== undefined) {
    obj = emptyFieldCheck(infoData, "socialInsuFlag", "有无社保");
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  //婚姻状况
  if (userModel.maritalStatus !== undefined) {
    obj = emptyFieldCheck(infoData, "maritalStatus", "婚姻状况");
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  //居民类型
  if (userModel.residentType !== undefined) {
    obj = emptyFieldCheck(infoData, "residentType", "居民类型");
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  //补偿型医疗险
  if (userModel.otherCompanyCompIns !== undefined) {
    obj = emptyFieldCheck(
      infoData,
      "otherCompanyCompIns",
      "是否有其他公司费用补偿型医疗险"
    );
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  //子女个数
  if (userModel.childrenNum !== undefined) {
    obj = emptyFieldCheck(infoData, "childrenNum", "子女个数");
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  //家庭年收入
  if (userModel.familyIncome !== undefined) {
    obj = emptyFieldCheck(infoData, "familyIncome", "家庭年收入");
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  //家庭收入来源
  if (userModel.familyIncomeSource !== undefined) {
    obj = emptyFieldCheck(infoData, "familyIncomeSource", "家庭收入来源");
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  //邮箱
  if (userModel.email !== undefined) {
    obj = emailCheck(infoData);
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  // 字段空校验
  if (userModel.crsIdType !== void 0) {
    obj = emptyFieldCheck(infoData, "crsIdType", "个税居民类型");
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
    // 税收文件填写
    const hasFile = getCacheValue("page", "hasResidentFile");
    if (hasFile) {
      obj = writeRevenueFileCheck(
        infoData,
        infoData.crsIdType,
        infoData.taxIdentInfo
      );
      if (!obj.status) return obj;
      if (obj.breakTips) {
        breakTips.push(obj.breakTips);
      }
    }
  }
  /**被保人特殊字段校验*/
  if (utype.indexOf("被保人") != -1) {
    if (userModel.relationToMain !== void 0) {
      obj = emptyFieldCheck(infoData, "relationToMain", "与主被保人的关系");
      if (!obj.status) return obj;
    }
    // 未成年，监护人信息
    if (userModel.guardianName !== void 0) {
      obj = minorJhrCheck(infoData, userModel);
      if (!obj.status) return obj;
    }
    const noticeMode = getCacheValue("page", "noticeMode");
    if (userModel.healthyStatus !== undefined && noticeMode == "2") {
      if (infoData.healthyStatus == "") {
        return createResult(false, `请确认健康告知`, "healthyStatus");
      }
    }
  }
  if (userModel.beneficialOrder !== void 0) {
    if (infoData.beneficialOrder === "") {
      return createResult(false, `请选择受益顺序`, "beneficialOrder");
    }
  }
  if (userModel.beneficialRate !== void 0) {
    if (infoData.beneficialRate <= 0) {
      return createResult(false, `受益比例必须大于0`, "beneficialRate");
    }
  }

  if (utype == "受益人") {
    obj = bnfsRuleCheck(infoData);
    if (!obj.status) return obj;
  }

  return {
    ...obj,
    breakTips: breakTips,
  };
};

export const bnfsRuleCheck = (userInfo) => {
  let obj = {
    msg: "",
    status: true,
    target: "",
  };
  let breakTips = [];
  const bbrArr = getCacheValue("insert", "bbrMultList");
  const bbrList = JSON.parse(JSON.stringify(bbrArr)),
    bbrLen = bbrList.length,
    bbrItem = bbrList[userInfo.syrToInsNo * 1];
  const sameNoBnfs = bbrItem.bnfs;
  let isSame = false;
  let fdArr = sameNoBnfs.filter((unit) => unit.idNum == userInfo.idNum);
  if (fdArr && fdArr.length > 1) {
    isSame = true;
  }
  let bbrIndex = "";
  if (bbrLen > 1) {
    bbrIndex = `被保人【${userInfo.syrToInsNo * 1 + 1}】`;
  }
  if (isSame) {
    return createResult(
      false,
      `根据保司要求:${bbrIndex}不能添加相同的受益人,请确认`
    );
  }
  let findList = [];
  // 上一步已排除同一人,此处不必再校验,否则只有一个受益人是不会校验
  findList = sameNoBnfs.filter(
    (unit) => unit.beneficialOrder == userInfo.beneficialOrder
  );
  const fdLen = findList.length,
    bnfNumMax = getCacheValue("page", "benefyNumMax");
  // 1.受益顺序
  if (fdLen > bnfNumMax) {
    return createResult(
      false,
      `根据保司要求:${bbrIndex}同一顺位最多可添加${bnfNumMax}位受益人,目前第${userInfo.beneficialOrder}顺位已有${fdLen}位受益人`
    );
  }
  // 2.受益比例: 同一顺序受益人份额加起来需要是100%
  if (fdLen > 0) {
    let totalRate = 0;
    findList.forEach((obj) => (totalRate += obj.beneficialRate - 0));
    if (totalRate !== 100) {
      return createResult(
        false,
        `同一顺序受益人的受益比例之和需是100,请检查相同顺位受益人的受益比例。`,
        "beneficialRate"
      );
    }
  }
  return { ...obj, breakTips };
};

/**
 * 保单信息校验
 * @param {*} strModel
 * @param {*} billInputObj
 * @returns
 */

export const validBillInfo = (strModel, billInputObj) => {
  let obj = {
    msg: "",
    status: true,
    target: "",
  };
  let breakTips = [];
  if (strModel.effectiveDate !== undefined) {
    obj = emptyFieldCheck(billInputObj, "effectiveDate", "生效日期");
    if (!obj.status) return obj;
  }
  if (strModel.expiryDate !== undefined) {
    obj = emptyFieldCheck(billInputObj, "expiryDate", "截止日期");
    if (!obj.status) return obj;
  }
  if (strModel.printPolType !== undefined) {
    obj = emptyFieldCheck(billInputObj, "printPolType", "保单类型");
    if (!obj.status) return obj;
  }
  if (strModel.qsContSelfFlag !== undefined) {
    if (!billInputObj.qsContSelfFlag) {
      return createResult(false, `请选择是否为自保件`, "qsContSelfFlag");
    }
  }
  if (strModel.payMode !== void 0) {
    obj = emptyFieldCheck(billInputObj, "payMode", "缴费方式");
    if (!obj.status) return obj;
  }
  if (strModel.bankCardType !== undefined) {
    if (!billInputObj.bankCardType) {
      return createResult(false, `请选择账号类型`, "bankCardType");
    }
  }
  if (strModel.bankAccNo !== undefined) {
    obj = emptyFieldCheck(billInputObj, "bankAccNo", "银行账号");
    if (!obj.status) return obj;
    const bankNoLen = billInputObj.bankAccNo.length;
    if (bankNoLen < 15 || bankNoLen > 21) {
      return createResult(false, `银行卡号位数错误`, "bankAccNo");
    }
  }
  if (strModel.bankCode !== undefined) {
    obj = emptyFieldCheck(billInputObj, "bankCode", "银行名称");
    if (!obj.status) return obj;
  }
  if (strModel.bankArea !== undefined) {
    obj = emptyFieldCheck(billInputObj, "bankArea", "开户行所在地");
    if (!obj.status) return obj;
  }
  if (strModel.firBankMobile !== undefined) {
    obj = emptyFieldCheck(billInputObj, "firBankMobile", "预留手机号");
    if (!obj.status) return obj;
    if (!regexMap.PHONE.test(billInputObj.firBankMobile)) {
      return createResult(false, `预留手机号格式错误`, "firBankMobile");
    }
  }
  if (strModel.autoPayFlag !== undefined) {
    obj = emptyFieldCheck(billInputObj, "autoPayFlag", "保费逾期未付处理方式");
    if (!obj.status) return obj;
  }
  if (strModel.expayMode !== undefined) {
    obj = emptyFieldCheck(billInputObj, "expayMode", "续期/续保交费形式");
    if (!obj.status) return obj;
  }
  if (strModel.aliveGetMode !== undefined) {
    obj = emptyFieldCheck(billInputObj, "aliveGetMode", "生存金是否转账授权");
    if (!obj.status) return obj;
    if (billInputObj.aliveGetMode == "Y") {
      if (strModel.bnfBankAccName !== undefined) {
        obj = emptyFieldCheck(
          billInputObj,
          "bnfBankAccName",
          "受益人授权账户名"
        );
        if (!obj.status) return obj;
      }
      if (strModel.bnfBankAccNo !== undefined) {
        obj = emptyFieldCheck(billInputObj, "bnfBankAccNo", "受益人授权账户");
        if (!obj.status) return obj;
      }
      if (strModel.bnfBankCode !== undefined) {
        if (
          billInputObj.bnfBankCode !== undefined &&
          billInputObj.bnfBankCode === ""
        ) {
          return createResult(false, `请选择受益人开户银行`, "bnfBankCode");
        }
      }
    }
  }
  return { ...obj, breakTips };
};

/**
 * 投保关系校验
 */
function tbRelateCheck(infoData, typeVal, userModel) {
  let obj = {
    target: "relationToAppnt",
    msg: "",
    status: true,
  };
  let relaValue = "";
  let targetUser = getCacheValue("insert", "applicant");
  let targetType = typeVal.indexOf("被保人") != -1 ? "投保人" : "被保人";

  if (typeVal == "受益人") {
    const get2 = getCacheValue("insert", "bbrMultList"),
      list2 = JSON.parse(JSON.stringify(get2));
    relaValue = infoData.relationToInsured;
    targetUser = list2[infoData.syrToInsNo * 1];
    obj.target = "relationToInsured";
  } else {
    relaValue = infoData.relationToAppnt;
    obj.target = "relationToAppnt";
  }

  if (!relaValue) {
    return createResult(
      false,
      `请选择${typeVal}与${targetType}的关系`,
      obj.target
    );
  }
  let ageVal = userAge(infoData.birthDate),
    targetAge = userAge(targetUser.birthDate);
  if (typeVal.indexOf("被保人") != -1) {
    obj = insrRelaToTbr(ageVal, relaValue);
    if (!obj.status) return obj;
    if (obj.breakTips) {
      breakTips.push(obj.breakTips);
    }
  }
  let ageInterval = getCacheValue("page", "ageInterval") || 18;
  // 父母时，投保人年龄不能小于被保险人
  if (relaValue == "1") {
    if (ageVal <= targetAge) {
      return createResult(
        false,
        `是${targetType}父母，年龄不能小于${targetType}`,
        obj.target
      );
    }
    if (ageVal - targetAge < ageInterval) {
      obj.breakTips = `是${targetType}父母，年龄相差小于${ageInterval}岁`;
    }
  } else if (relaValue == "2") {
    // 关系为子女时， 子女年龄不能大于父母人；
    if (ageVal >= targetAge) {
      return createResult(
        false,
        `是${targetType}子女，年龄不能大于${targetType}`,
        obj.target
      );
    }
    const diffAge = targetAge * 1 - ageVal * 1;
    if (diffAge < ageInterval) {
      obj.breakTips = `是${targetType}子女，年龄相差小于${ageInterval}岁`;
    }
  } else if (relaValue == "0") {
    // 关系为配偶时，性别不能相同；
    if (infoData.sex == targetUser.sex) {
      return createResult(false, `配偶关系，性别不能相同`, obj.target);
    }
    // 配偶--->婚姻状况
    if (userModel.maritalStatus !== undefined) {
      if (typeVal.indexOf("被保人") != -1) {
        if (!["1", "10"].includes(infoData.maritalStatus)) {
          return createResult(
            false,
            `配偶关系，被保人婚姻状况不能为${infoData.maritalStatusName}`,
            "maritalStatus"
          );
        }
        if (!["1", "10"].includes(targetUser.maritalStatus)) {
          obj.msg = `配偶关系，投保人婚姻状况不能为${targetUser.maritalStatusName}`;
          obj.status = false;
          obj.target = "maritalStatus";
          obj.targetUser = "tbr";
          return obj;
        }
      }
    }
  }
  return createResult(true);
}

/**
 * 姓名校验
 * @param {*} nameValue
 * @param {*} typeVal
 * @returns
 */

export const nameCheckRule = (nameValue) => {
  // 预编译正则表达式
  const maxNum = getCacheValue("page", "nameMaxLength") || 20;
  // 空值检查
  if (!nameValue || nameValue.trim() === "") {
    return createResult(false, `姓名不能为空`);
  }
  // 中文姓名规则
  if (regexMap.isChinese(nameValue)) {
    if (nameValue.length < 2) {
      return createResult(false, `姓名少于两个汉字`);
    }
    if (nameValue.length > maxNum) {
      return createResult(false, `姓名长度不能超过${maxNum}个汉字`);
    }
    if (!regexMap.CHINA.test(nameValue)) {
      return createResult(false, `姓名输入有误`);
    }
  }
  // 英文姓名规则
  else {
    if (nameValue.length < 3) {
      return createResult(false, `姓名小于3个字符`);
    }
    if (!regexMap.ENG.test(nameValue) || regexMap.BLANK2.test(nameValue)) {
      return createResult(false, `姓名输入有误`);
    }
    if (nameValue.length > 40) {
      return createResult(false, `姓名长度超过最大限制`);
    }
  }
  return createResult(true);
};

/**
 * 证件号码校验
 * @param {*} userInfo
 * @param {*} userType
 * @returns
 */

export const idNumCheck = (userInfo) => {
  if (!userInfo || !userInfo.idNum || userInfo.idNum === "") {
    return createResult(false, `请输入证件号码`, "idNum");
  }
  // console.log("userInfo", userInfo.idType);
  try {
    switch (userInfo.idType) {
      case "0":
      case "3":
        if (!IdentityCodeValid(userInfo.idNum)) {
          return createResult(false, `身份证校验不通过`, "idNum");
        }
        break;
      case "11":
        const bronResult = validateWithRegex(
          userInfo.idNum,
          regexMap.bronReg,
          `证件号码不正确`
        );
        if (bronResult) return bronResult;
        break;
      case "2": // 军人证
        if (!regexMap.soldierReg.test(userInfo.idNum)) {
          return createResult(false, `证件号码不正确`, "idNum");
        }
        break;
      case "10": // 回乡证
        const nationality = userInfo.nationality || "";
        const homeResult = validateWithRegex(
          userInfo.idNum,
          nationality.toUpperCase() === "MAC"
            ? regexMap.macReg
            : regexMap.hkgReg,
          `证件号码不正确`
        );
        if (homeResult) return homeResult;
        break;
      case "9": // 台胞证
        const taiwanResult = validateWithRegex(
          userInfo.idNum,
          regexMap.taiwanReg,
          `证件号码不正确`
        );
        if (taiwanResult) return taiwanResult;
        break;
      case "16": // 外国人永久居留身份证
        const foreignerResult = validateWithRegex(
          userInfo.idNum,
          regexMap.foreignerReg,
          `证件号码不正确`
        );
        if (foreignerResult) return foreignerResult;
        break;
      case "6": // 港澳居民居住证（香港）
      case "7": // 港澳居民居住证（澳门）
      case "29": // 港澳居民居住证
      case "8": // 港澳居民居住证
        if (userInfo.idNum.length !== 18) {
          return createResult(false, `证件号码不正确`, "idNum");
        }
        const starStr =
          userInfo.nationality?.toUpperCase() === "MAC"
            ? "820000"
            : userInfo.nationality?.toUpperCase() === "HKG"
            ? "810000"
            : "830000";
        if (!userInfo.idNum.startsWith(starStr)) {
          return createResult(false, `证件号码不正确`, "idNum");
        }
        break;
      default:
        break;
    }
  } catch (error) {
    // 捕获异常并返回错误结果
    console.warn("验证失败：", error);
  }
  return createResult(true);
};
// 定义通用验证函数
const validateWithRegex = (idNum, regex, errorMessage) => {
  if (!regex.test(idNum)) {
    return createResult(false, errorMessage, "idNum");
  }
  return null; // 验证通过返回 null
};
/**
 * 证件止期校验
 * @param {*} userInfo
 * @param {*} userType
 * @returns
 */
function validDateEndCheck(userInfo) {
  var idLongTime = getCacheValue("dictionary", "longTime");
  if (userInfo.validDateEnd === "") {
    return createResult(false, `请选择证件有效日期止期`, "validDateEnd");
  }
  const appGapDay = dayDiffValue(
    new Date(),
    new Date(userInfo.validDateEnd.replace(/-/g, "/"))
  );
  if (appGapDay < 1) {
    return createResult(false, `证件已到期，请及时更换证件`, "validDateEnd");
  }
  const tbAge = userAge(userInfo.birthDate);

  // 身份证有效期
  if (userInfo.idType == "0") {
    let appGapYear = yearDiffValue(
      new Date(userInfo.validDateEnd.replace(/-/g, "/")),
      new Date()
    );
    // 如果有起期 严格按照身份证规则
    if (userInfo.validDate) {
      appGapYear = yearDiffValue(
        new Date(userInfo.validDateEnd.replace(/-/g, "/")),
        new Date(userInfo.validDate.replace(/-/g, "/"))
      );
    }
    // 1.被保时年龄小于16周岁，证件有效期超过投保时间+5年  止期年-起期年=5
    if (tbAge < 16) {
      if (appGapYear > 5) {
        return createResult(false, `证件有效期错误`, "validDateEnd");
      }
    } else if (tbAge >= 16 && tbAge <= 25) {
      // 2.被保时年龄大于等于16周岁且小于等于25周岁时，证件有效期超过投保时间+10年  止期年-起期年=10
      if (appGapYear > 10) {
        return createResult(false, `证件有效期错误`, "validDateEnd");
      }
    } else if (tbAge > 25 && tbAge <= 45) {
      // 2.被保时年龄大于25周岁小于等于45周岁时，证件有效期超过投保时间+20年； 止期年-起期年=20
      if (appGapYear > 20) {
        return createResult(false, `证件有效期错误`, "validDateEnd");
      }
    } else if (tbAge >= 46) {
      // 3.被保时年龄大于等于46周岁时，对于非长期，若证件有效期日期-投保日大于20年；非长期证件时，证件有效期截止日不能小于当日。（长期传值必须为9999-12-31）
      if (appGapYear > 20 && userInfo.validDateEnd !== idLongTime) {
        return createResult(false, `证件有效期错误`, "validDateEnd");
      }
    }
  }
  return createResult(true);
}

/**
 * 地址校验
 * @param {*} userInfo
 * @param {*} userType
 * @returns
 */
export const addrCheck = (userInfo, keyName) => {
  let obj = {
    msg: "",
    target: keyName,
    status: true,
  };
  // console.log("addrCheck", userInfo);
  const tempDic = getCacheValue("dictionary"),
    addrValue = userInfo[keyName] || "",
    maxNum = tempDic.addrSameStrMaxNum || 5;
  // 区域校验
  if (keyName == "permanentAddress" && !userInfo.province) {
    return createResult(false, `请选择现居地址`, "areaName");
  }
  if (keyName == "postalPermanentAddress" && !userInfo.postalProvince) {
    return createResult(false, `请选择通讯地址`, "postalAreaName");
  }
  if (keyName == "homePermanentAddress" && !userInfo.homeProvince) {
    return createResult(false, `请选择家庭地址`, "homeAreaName");
  }
  let addrType = "现居地址-";
  if (keyName == "postalPermanentAddress") {
    addrType = "通讯地址-";
  } else if (keyName == "homePermanentAddress") {
    addrType = "家庭地址-";
  }
  if (addrValue.length < 6) {
    return createResult(false, `${addrType}详细地址不少于6个字符`, keyName);
  }
  if (checkStrMaxNum(addrValue, maxNum)) {
    return createResult(
      false,
      `${addrType}详细地址中同一个字（包括汉字、字母、数字）连续出现不能超过${maxNum}次`,
      keyName
    );
  }
  // 地址包含关键字
  let rules2 = tempDic.detailAddrRule.split(",");
  for (let i = 0; i < rules2.length; i++) {
    if (!addLabel(addrValue, rules2[i])) {
      obj.msg = ``;
      obj.status = false;
      return createResult(
        false,
        `${addrType}详细地址必须包含${rules2[i]}`,
        keyName
      );
    }
  }
  return createResult(true);
};

/**
 * 销售区域校验
 * @param {*} userInfo
 * @param {*} userType
 * @returns
 */
export const insuAddrCheck = (userInfo) => {
  let checkText = "与本产品销售区域",
    check2Text = "不一致，请确认",
    fdAraeName = "";
  const caliArea = getCacheValue("page", "calibrationArea") || [],
    saleArea = getCacheValue("varietyInfo", "provinces") || [],
    saleProvNo = getCacheValue("agent", "saleProvinceNo") || "";
  if (caliArea.length > 0) {
    if (saleArea.length > 0) {
      let fdArae = saleArea.find((ele) => ele.provinceNo == saleProvNo);
      if (fdArae && fdArae.provinceName) {
        fdAraeName = fdArae.provinceName;
      }
    }
    if (fdAraeName) {
      checkText += `【 ${fdAraeName} 】${check2Text}`;
    } else {
      checkText += `${check2Text}`;
    }
    // 现居
    if (
      userInfo.areaName &&
      userInfo.province &&
      caliArea.includes("areaName")
    ) {
      if (userInfo.province != saleProvNo) {
        return createResult(false, `现居地址${checkText}`, "areaName");
      }
    }
    if (
      userInfo.postalAreaName &&
      userInfo.postalProvince &&
      caliArea.includes("postalAreaName")
    ) {
      if (userInfo.postalProvince != saleProvNo) {
        return createResult(false, `通讯地址${checkText}`, "postalAreaName");
      }
    }
    if (
      userInfo.homeAreaName &&
      userInfo.homeProvince &&
      caliArea.includes("homeAreaName")
    ) {
      if (userInfo.homeProvince != saleProvNo) {
        return createResult(false, `家庭地址${checkText}`, "homeAreaName");
      }
    }
  }
  return createResult(true);
};

/**
 * 地址关键字校验
 * @param {*} str
 * @param {*} ruleStr
 * @returns
 */
function addLabel(str, ruleStr) {
  const rulesArr = ruleStr.split("/");
  let resVal = false;
  for (let i = 0; i < rulesArr.length; i++) {
    if (str.indexOf(rulesArr[i]) !== -1) {
      resVal = true;
      break;
    }
  }
  return resVal;
}

/**
 * 邮箱校验
 * @param {*} userInfo
 * @param {*} userType
 * @returns
 */
export const emailCheck = (userInfo) => {
  if (!userInfo.email) {
    return createResult(false, `请输入邮箱`, "email");
  } else if (!regexMap.EMAIL.test(userInfo.email)) {
    return createResult(false, `邮箱格式错误`, "email");
  }
  return createResult(true);
};

export const minorJhrCheck = (userInfo, userModel) => {
  const ageLimit = getCacheValue("page", "minorAge") || 18,
    bbrAge = userAge(userInfo.birthDate);
  if (bbrAge < ageLimit) {
    if (userInfo.guardianName == "" || userInfo.guardianIdNo == "") {
      return createResult(false, `未成年，请填写监护人信息`, "guardianName");
    }
    if (
      userModel.guardianRelationToInsured !== void 0 &&
      userInfo.guardianRelationToInsured == ""
    ) {
      return createResult(
        false,
        `请选择被保人与监护人关系`,
        "guardianRelationToInsured"
      );
    }
  }
  return createResult(true);
};

// 封装返回对象的方法
export const createResult = (status = true, msg = "", target = "name") => ({
  msg,
  target,
  status,
});
